import 'dart:ui';

import 'package:encrypt/encrypt.dart';

extension StringExtension on String {
  /// String to Color
  Color? toColor() {
    var hexColor = replaceAll('#', '');
    if (hexColor.length == 6) {
      hexColor = 'FF$hexColor';
    }
    if (hexColor.length == 8) {
      return Color(int.parse('0x$hexColor'));
    }

    return null;
  }

  /// 校验手机号
  bool isPhone() {
    RegExp exp = RegExp(r"^1[0-9]\d{9}$");
    return exp.hasMatch(this);
  }

  /// 校验邮箱
  bool isEmail() {
    RegExp exp = RegExp(r"^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$");
    return exp.hasMatch(this);
  }

  /// 校验身份证
  bool isID() {
    RegExp exp = RegExp(r"(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)");
    return exp.hasMatch(this);
  }

  /// split
  List<String> splitEx(RegExp regExp) {
    var allMatches = regExp.allMatches(this);

    List<String> splitStrList = [];
    int start = 0;
    for (var element in allMatches) {
      if (start != element.start) {
        splitStrList.add(substring(start, element.start));
      }

      splitStrList.add(substring(element.start, element.end));
      start = element.end;
    }
    if (start != length) {
      splitStrList.add(substring(start));
    }

    return splitStrList;
  }

  String getPhoneReg() {
    if (length <= 7) {
      return this;
    }
    return replaceFirst(RegExp(r'\d{4}'), '****', 3);
  }

  int findNum() {
    if (isEmpty) {
      return 0;
    }
    List<String> list = split('');
    for (var element in list) {
      int? num = int.tryParse(element);
      if (num != null) {
        return num;
      }
    }
    return 0;
  }

  String aesDecrypt(String key) {
    final aesKey = Key.fromUtf8(key);
    final encrypter = Encrypter(AES(aesKey, mode: AESMode.ecb, padding: null));

    Encrypted encrypted = Encrypted.fromBase64(this);
    return encrypter.decrypt(encrypted);
  }
}
